%%%-------------------------------------------------------------------
%%% @author yujian
%%% @doc
%%% Created : 17. 二月 2016 下午3:36
%%%-------------------------------------------------------------------
-module(ejieba_http).

-export([init/2]).

init(Req, Opts) ->
    [{<<"keywords">>, KeyWords}, {<<"type">>, Type}] =
        case cowboy_req:has_body(Req) of
            true ->
                %% 需要区分这两种情况, 1 正常情况， 2 表单上传
                ContentType = cowboy_req:header(<<"content-type">>, Req),
                case binary:match(ContentType, <<"multipart/form-data">>) of
                    nomatch ->
                        {ok, PostVals, _Req2} = cowboy_req:read_body(Req),
                        cow_qs:parse_qs(PostVals);
                    _ ->
                        {Result, _Req2} = acc_multipart(Req, []),
                        Result
                end;
            false ->
                []
        end,
    
    Cut = if
              Type =:= <<"KEYWORD">> -> ejieba:keyword(KeyWords);
              Type =:= <<"TAGGING">> -> ejieba:target(KeyWords);
              true -> ejieba:cut(KeyWords, binary_to_integer(Type))
          end,
    io:format("111:~p~n", [Cut]),
    Body = ret(Cut, []),
    {ok,
        cowboy_req:reply(200,
            #{<<"Access-Control-Allow-Origin">> => <<"*">>,
                <<"Access-Control-Allow-Methods">> =><<"GET,POST">>,
                <<"Content-Type">> => <<"application/json">>},
            Body, Req),
        Opts}.

ret([H], Data) -> lists:reverse([H, "  " | Data]);
ret([H | R], Data) ->
    ret(R, [H, "  " | Data]).

acc_multipart(Req, Acc) ->
    case cowboy_req:read_part(Req) of
        {ok, Headers, Req2} ->
            {ok, Body, Req3} = cowboy_req:read_part_body(Req2),
            acc_multipart(Req3, [{Headers, Body} | Acc]);
        {done, Req2} ->
            {lists:reverse(Acc), Req2}
    end.